<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true">
      <el-form-item label="模型名称" prop="modelName">
        <el-input
          v-model="queryParams.modelName"
          placeholder="请输入模型名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleInitCache"
          v-hasPermi="['system:role:export']"
        >刷新缓存
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="false"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:role:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getPage"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="page" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模型名称" prop="modelName" :show-overflow-tooltip="true" width="240"/>
      <el-table-column label="模型功能说明" prop="modelDesc" width="350"/>
      <el-table-column label="模型功能说明文档" prop="modelDescFileId" width="200">
        <template slot-scope="scope"
                  v-if="scope.row.roleId !== 1 && scope.row.modelDescFileId !== ''
                  &&  typeof (scope.row.modelDescFileId) !== 'undefined' &&  scope.row.modelDescFileId !== null">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row.modelDescFileId)"
            v-hasPermi="['system:role:remove']"
          >下载
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="模型功能jar" prop="handleFileId" width="200">
        <template slot-scope="scope"
                  v-if="scope.row.roleId !== 1 && scope.row.modelFileId !== ''
                    &&  typeof (scope.row.modelFileId) !== 'undefined' &&  scope.row.modelFileId !== null">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row.modelFileId)"
            v-hasPermi="['system:role:remove']"
          >下载
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="是否启用" align="center" width="130">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enable"
            :active-value=1 :inactive-value=0
            @change="handleEnableStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:role:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:role:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRelModelSt(scope.row)"
            v-hasPermi="['system:role:edit']"
          >模型关联配置
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getPage"
    />

    <!-- 添加或修改解析组元素顺序对话框 -->
    <el-dialog :visible.sync="open" :title="title" width="800px" append-to-body>
      <div>
        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="160px">
          <el-col :span="24">
            <el-form-item label="模型名称" prop="modelName">
              <el-input v-model="form.modelName" placeholder="请输入规则名称" show-word-limit clearable
                        :style="{width: '100%'}"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模型功能简要说明" prop="modelDesc">
              <el-input v-model="form.modelDesc" placeholder="请输入规则功能简要说明" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模型功能说明文档上传" prop="modelDescFileId">
              <file-upload @input="descFileCallback" :limit="1"
                           v-model="form.modelDescFileId" :fileType="handleDescFileLimitType"
                           :fileSize="100"></file-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="模型功能jar上传" prop="modelFileId">
              <file-upload @input="modelFileCallback" :limit="1"
                           v-model="form.modelFileId" :fileType="fileLimitType"
                           :fileSize="100"></file-upload>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="relStOpen" title="计算模型关联测站配置" width="800px" append-to-body>
      <el-transfer v-model="relModelStForm.stCodes" :titles="['未选中测站列表', '已选测站列表']"
                   filterable :props="transferProps" :data="allStationList"
                   filter-placeholder="请输入测站名称" :filter-method="transferFilterMethod"/>
      <div slot="footer">
        <el-button @click="cancel">取消</el-button>
        <el-button type="primary" @click="addRelModelSt">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    page,
    getComputeModel,
    insertComputeModel,
    updateComputeModel,
    delComputeModel,
    initCache,
    getRelModelStListByModelId,
    insertRelComputeModelSt,
    enableStatusChange
  } from "@/api/quality/computemodel";
  import {
    fileDownload,
    fileShow
  } from "@/api/tool/file/file";
  import FileUpload from '@/components/FileUpload/index.vue';
  import {
    getAllStation
  } from "@/api/equipmentmanagement/equipment";

  export default {
    components: {
      FileUpload,
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 表格数据
        page: null,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {
          modelName: '',
          modelDesc: '',
          modelDescFileId: '',
          modelFileId: '',
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          modelName: '',
        },
        dialogType: "",
        // 表单校验
        rules: {
          modelName: [{
            required: true,
            message: '请输入计算模型名称',
            trigger: 'blur'
          }],
          modelDesc: [{
            required: true,
            message: '请输入计算模型简要描述',
            trigger: 'blur'
          }],
          modelFileId: [{
            required: true,
            message: '请上传计算模型依赖jar',
            trigger: 'blur'
          }],
        },
        ruleTypeOptions: [{
          value: 'jar',
          label: 'jar'
        }, {
          value: 'local',
          label: 'local'
        }],
        handleDescFileLimitType: ['txt', 'doc', 'docx', 'md', 'pdf'],
        fileLimitType: ['jar'],
        allStationList: [],
        relStOpen: false,
        relModelStForm: {
          stCodes: []
        },
        modelId: '',
        transferProps: {
          key: 'stCd',
          label: 'stName'
        },
      };
    },
    created() {
      this.getPage();
      this.getAllStation();
    },

    methods: {
      /** 查询分页列表 */
      getPage() {
        this.loading = true;
        page(this.queryParams).then(response => {
            this.page = response.rows;
            this.total = response.total;
            this.loading = false;
          }
        );
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          ids: undefined,
          analysisGroupName: undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getPage();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.title = "新增计算模型";
        this.open = true;
        this.dialogType = "add";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids;
        getComputeModel(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改计算模型";
          this.dialogType = "update";
        });
      },
      /** 查看预览文件操作 */
      handleShow(row) {
        this.reset();
        const id = row.id || this.ids;
        fileShow(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改计算模型";
          this.dialogType = "update";
        });
      },
      /** 下载文件操作 */
      handleDownload(handleDescFileId) {
        fileDownload(handleDescFileId);
      },
      // 计算模型启用状态修改
      handleEnableStatusChange(row) {
        let text = row.enable === 1 ? "启用" : "停用";
        this.$modal.confirm('确认要' + text + '模型' + row.modelName + '"吗？')
          .then(function () {
            return enableStatusChange(row);
          }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function () {
          row.enable = row.enable === 1 ? 0 : 1;
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        let that = this;
        that.$refs["form"].validate(valid => {
          if (valid) {
            if ('update' === that.dialogType) {
              updateComputeModel(that.form).then(response => {
                that.$modal.msgSuccess("修改成功");
                that.open = false;
                that.getPage();
              });
            } else {
              insertComputeModel(that.form).then(response => {
                that.$modal.msgSuccess("新增成功");
                that.open = false;
                that.getPage();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const id = row.id || this.ids;
        this.$modal.confirm('是否确认删除？').then(function () {
          return delComputeModel(id);
        }).then(() => {
          this.getPage();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      },
      handleRelModelSt(row) {
        const id = row.id;
        this.relStOpen = true;
        this.getRelModelStListByModelId(id)
      },
      /** 查询所有接入测站列表 */
      getAllStation() {
        getAllStation().then(response => {
          this.allStationList = response.data;
        });
      },
      /** 查询该解析组下所有接入测站列表 */
      getRelModelStListByModelId(id) {
        this.relModelStForm.stCodes = [];
        this.modelId = id;
        getRelModelStListByModelId(id).then(response => {
          this.relModelStForm.stCodes = response.data;
        });
      },
      transferFilterMethod(query, item) {
        const stName = item.stName;
        if (stName !== null && stName !== '' && typeof(stName) !== 'undefined') {
          return item.stName.indexOf(query) > -1;
        }
        return 0;
      },
      addRelModelSt: function () {
        let that = this;
        const stCodes = that.relModelStForm.stCodes;
        const modelId = that.modelId;
        if (stCodes === null || typeof (stCodes) === 'undefined' || stCodes.length < 1) {
          that.relStOpen = false;
        } else {
          insertRelComputeModelSt(stCodes, modelId).then(response => {
            that.$modal.msgSuccess("配置成功");
            that.relStOpen = false;
            that.getPage();
          });
        }
      },
      descFileCallback(fileId) {
        if (fileId.indexOf(",") > -1) {
          fileId = fileId.substr(0, fileId.indexOf(","));
        }
        this.form.modelDescFileId = fileId;
      },
      modelFileCallback(fileId) {
        if (fileId.indexOf(",") > -1) {
          fileId = fileId.substr(0, fileId.indexOf(","));
        }
        this.form.modelFileId = fileId;
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.relStOpen = false;
        this.reset();
      },
      handleInitCache() {
        this.$confirm('此操作将删除缓存中原有配置，并从数据库中加载最新配置信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          initCache().then(response => {
            this.$message({
              type: 'success',
              message: '初始化成功!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('system/user/export', {
          ...this.queryParams
        }, `user_${new Date().getTime()}.xlsx`)
      },
    }
  };
</script>


<style lang='scss' scoped>
  body, html {
    margin: 0;
    padding: 0;
    background: #fff;
    -moz-osx-font-smoothing: grayscale;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
    font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
  }

  input, textarea {
    font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif, Apple Color Emoji, Segoe UI Emoji;
  }

  .detailElementStyle {
    min-height: 800px;
  }

  .el-dialog {
    min-height: 500px;
  }

  .el-transfer {
    width: 100%;
    ::v-deep .el-transfer-panel {
      width: 37%;
      height: 100%;
    }
  }
</style>
